package com.blb.day20231107login.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.day20231107login.entity.Permission;
import com.blb.day20231107login.entity.ResponseResult;
import com.blb.day20231107login.entity.User;
import com.blb.day20231107login.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @GetMapping("/users")
    public ResponseResult<List<User>> findAll(){
        List<User> users = userService.list();
        return ResponseResult.ok(users);
    }

    @GetMapping("/users-page")
    public ResponseResult<Page<User>> findPage(@RequestParam(required = false,defaultValue = "1")Long current,
                                               @RequestParam(required = false,defaultValue = "5")Long size){
        Page<User> users = userService.page(new Page<User>(current,size));
        return ResponseResult.ok(users);
    }

    @PutMapping("/user")
    public ResponseResult<String> update(@RequestBody User user){
        userService.updateById(user);
        return ResponseResult.ok("ok");
    }

    @PostMapping("/user")
    public ResponseResult<String> add(@RequestBody User user){
        user.setPassword(encoder.encode(user.getPassword()));
        userService.save(user);
        return ResponseResult.ok("ok");
    }

    @DeleteMapping("/user/{id}")
    public ResponseResult<String> delete(@PathVariable Long id){
        userService.removeById(id);
        return ResponseResult.ok("ok");
    }

    @GetMapping("/user-permissions/{username}")
    public ResponseResult<List<Permission>> findPermissionsByUsername(@PathVariable String username){
        List<Permission> permissions = userService.getPermissionsWithChildrenByUsername(username);
        return ResponseResult.ok(permissions);
    }
}
